const Controller = require('./baseController');



const userValidate = {
  username: {
    type: 'string',
    required: true
  },
  email: {
    type: 'email',
    required: true
  },
  password: {
    type: 'string',
    required: true
  }

}

class UserController extends Controller {
  async create() {
    let data = this.ctx.request.body
    this.ctx.validate(userValidate)
    data.insert_time = new Date()
    data.last_time = new Date()
    data.headImage = ''
    data.password = this.ctx.app.md5(data.password)
    try {
      let userInfo = await this.ctx.model.User.create(data)
      let token = this.ctx.app.jwt.sign({
        userInfo,
        over_time: new Date().getTime() + this.oneDay
      }, this.ctx.app.config.jwt.secret)
      userInfo.token = token
      this.success(userInfo)
    } catch (e) {
      this.error((e.message.includes('email') ? '邮箱' : '昵称') + '已被注册！')
    }
  }
  async list() {
    let data = this.ctx.request.body
    if (!data['email'] || !data['password'])
      return this.error('邮箱或密码不能为空')
    let userInfo = await this.ctx.model.User.findOne({
      email: data['email']
    })
    if (!userInfo) return this.error('用户不存在')
    else if (userInfo.password !== this.ctx.app.md5(data['password'])) return this.error('密码错误')
    else {
      let token = this.ctx.app.jwt.sign({
        userInfo,
        over_time: new Date().getTime() + this.oneDay
      }, this.ctx.app.config.jwt.secret)
      userInfo.token = token
      return this.success(userInfo)
    }
  }
  async badLogin() {
    return this.error('登陆超时', '-2')
  }
}

module.exports = UserController;